package com.chuangjian.hire.coupon.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuangjian.hire.common.exceptionEnum.ApiExceptionEnum;
import com.chuangjian.hire.common.exption.ApiException;
import com.chuangjian.hire.coupon.dao.UsersCouponMapper;
import com.chuangjian.hire.coupon.domain.UsersCouponDO;
import com.chuangjian.hire.coupon.enums.CouponStatus;
import com.chuangjian.hire.coupon.service.UsersCouponService;
import com.chuangjian.hire.users.dto.UserDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * FileName: UsersCouponBusiness
 * Description:
 *
 * @author: CodeGenerator
 * @date: 2020/07/14 10:14
 * Copyright (C) 杭州同基汽车科技有限公司
 */
@Transactional
@Service("usersCouponService")
public class UsersCouponServiceImpl extends ServiceImpl<UsersCouponMapper, UsersCouponDO> implements UsersCouponService {

    @Override
    public List<UsersCouponDO> getUserCouponList(Long userId) {
        Date now = new Date();
        return list(
                Wrappers.<UsersCouponDO>lambdaQuery()
                        .eq(UsersCouponDO::getUserId, userId)
                        .eq(UsersCouponDO::getStatus, CouponStatus.VALID.getValue())
                        .gt(UsersCouponDO::getStartDate, now)
                        .lt(UsersCouponDO::getEndDate, now)
        );
    }

    @Override
    public Boolean useCoupon(Long userCouponId, BigDecimal amount, Long userId) {
        UsersCouponDO coupon = getById(userCouponId);
        if (coupon == null) {
            throw new ApiException(ApiExceptionEnum.COUPON_ERROR);
        }
        if (!coupon.getAmount().equals(amount)) {
            throw new ApiException(ApiExceptionEnum.COUPON_ERROR);
        }
        if (!coupon.getStatus().equals(CouponStatus.VALID.getValue())) {
            throw new ApiException(ApiExceptionEnum.COUPON_ERROR);
        }
        coupon.setStatus(CouponStatus.USED.getValue());
        return updateById(coupon);
    }


    private UsersCouponDO getCoupon(Long couponId, Long userId) {
        return getOne(Wrappers.<UsersCouponDO>lambdaQuery()
                .eq(UsersCouponDO::getCouponId, couponId)
                .eq(UsersCouponDO::getUserId, userId)
        );
    }

    @Override
    public Boolean recovery(Long userCouponId, Long userId) {
        UsersCouponDO coupon = getById(userCouponId);
        coupon.setStatus(CouponStatus.VALID.getValue());
        return updateById(coupon);
    }
}
